Variadic Tuple Types
TypeScript 4.0
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types
1つ目の変更
タプルのspreadがgenericになった
code:ts
function tail<T extends any[]>(arr: readonly any, ...T) {
const _ignored, ...rest = arr;
return rest;
}
const myTuple = 1, 2, 3, 4 as const;
const myArray = "hello", "world";
const r1 = tail(myTuple);
// ^ = const r1: 2, 3, 4
const r2 = tail(...myTuple, ...myArray as const);
// ^ = const r2: [2, 3, 4, ...string[]]
2つ目の変更
rest elementsがタプル内のどこでも使えるようになった
code:ts
type Strings = string, string;
type Numbers = number, number;
type StrStrNumNumBool = ...Strings, ...Numbers, boolean;
これが型でできるようになった
従来は末尾でしかできなかった
concatの型定義もこのとおり
code:ts
type Arr = readonly any[];
function concat<T extends Arr, U extends Arr>(arr1: T, arr2: U): ...T, ...U {
return ...arr1, ...arr2;
}
code:ts
type Arr = readonly unknown[];
function partialCall<T extends Arr, U extends Arr, R>(
f: (...args: ...T, ...U) => R,
...headArgs: T
) {
return (...tailArgs: U) => f(...headArgs, ...tailArgs);
}
部分適用の型もしっかり通る
https://qiita.com/uhyo/items/7e31bbd93a80ce9cec84